<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['classes:ClassUser:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['classes:ClassUser:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['classes:ClassUser:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ClassUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="用户昵称" align="center" prop="userNickName" />
      <el-table-column label="用户账户" align="center" prop="userName" />
      <el-table-column label="是否为管理员" align="center" prop="userType">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.userType" :active-value="1" :inactive-value="0" active-color="#02538C"
            inactive-color="#B9B9B9" @change="changeSwitch(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['classes:ClassUser:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['classes:ClassUser:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改班级用户连接对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-table v-loading="userLoading" :data="userList" @selection-change="handleUserSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
          <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClassUser, getClassUser, delClassUser, addClassUser, updateClassUser, listUnlisted, addClassUserBatch } from "@/api/classes/ClassUser";

export default {
  name: "ClassUser",
  data() {
    return {
      classId: null,
      // 遮罩层
      loading: true,
      // 
      userLoading: true,
      // 选中数组
      ids: [],
      //
      addIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级用户连接表格数据
      ClassUserList: [],
      userList: [],
      deleteUsers: [],
      addUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userType: null,
        classId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userType: [
          { required: true, message: "用户类型，0成员，1管理员不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.classId = this.$route.params && this.$route.params.classId;
    if (this.classId) {
      this.getList();
    }
  },
  methods: {
    /** 查询班级用户连接列表 */
    getList() {
      this.loading = true;
      this.queryParams.classId = this.classId;
      listClassUser(this.queryParams).then(response => {
        this.ClassUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        classId: this.classId,
        userId: null,
        userType: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.deleteUsers = [];
      for (const id of this.ids) {
        this.deleteUsers.push({ classId: this.classId, userId: id });
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleUserSelectionChange(selection) {
      this.addIds = selection.map(item => item.userId)
      this.addUserList = []
      for (const id of this.addIds) {
        this.addUserList.push({ classId: this.classId, userId: id, userType: 0 });
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加用户";
      this.userLoading = true;
      listUnlisted(this.classId).then(res => {
        console.log(res.data)
        this.userList = res.data;
        this.userLoading = false;
      })
    },
    /** 修改按钮操作 */
    changeSwitch(row) {
      const userId = row.userId;
      const userType = row.userType;
      updateClassUser({ classId: this.classId, userId, userType }).then(response => {
        this.$modal.msgSuccess("修改成功");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addClassUserBatch(this.addUserList).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.addUserList = [];
            this.open = false;
            this.getList();
          }).catch(() => { this.addUserList = []; });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let userId = row.userId;
      if (userId) {
        let that = this
        this.$modal.confirm('是否确认删除?').then(function () {
          return delClassUser([{ classId: that.classId, userId: userId }]);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      } else {
        if (this.deleteUsers.length != 0) {
          let that = this
          this.$modal.confirm('是否确认删除').then(function () {
            return delClassUser(that.deleteUsers);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => { });
        }
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('classes/ClassUser/export', {
        ...this.queryParams
      }, `ClassUser_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
